/**
 * 登录拦截器
 */

// 页面白名单，不登录也能访问的页面
const whiteList = [
	'/pages/launch',
	'/pages/login',
	'/pages/shop/index',
	'/pages/shop/product',
	'/pages/discover/index',
	'/pages/discover/article',
	'/pages/uc/index',
	'/pages/cart/index'
];

function hasPermission(url) {
	// 去除url后的参数
	if(url.indexOf('?') !== -1) {
		url = url.substr(0, url.indexOf('?'));
	}
	
	// 如果请求的url在白名单中，直接返回true
	if(whiteList.indexOf(url) !== -1) {
		return true;
	}
	
	// 从本地获取token判断是否登录
	try {
		const token = uni.getStorageSync('token');
		console.log('拦截器token:' + token);
		if(token && token.length > 0) {
			return true;
		}
	} catch(e) {
		return false;
	}
	
	return false;
}

const apiList = ['navigateTo', 'switchTab', 'redirectTo'];
apiList.forEach((api)=>{
	uni.addInterceptor(api, {
		invoke(e) {
			if(!hasPermission(e.url)) {
				uni.navigateTo({
					url: '/pages/login'
				})
				return false;
			}
		}
	});
});





